<script setup lang="ts">
import { reactive } from "vue";
import { ElMessage } from "element-plus";
import { changePassword } from '@/api/userInfo.js'
import { useUserInfoStore } from '@/store/userInfo.js'
import { useRouter } from "vue-router";

const router = useRouter()
//获取用户信息
const userStore = useUserInfoStore()
//修改数据
interface modifyData {
    oldPassword: string,
    newPassword: string,
}

const modifyData: modifyData = reactive({
    oldPassword: '',
    newPassword: '',
})
//弹框状态,默认关闭
const state = reactive({
    changeTip: false
})
//打开忘记密码弹框
const open = () => {
    state.changeTip = true;
}
defineExpose({
    open
})
//表单规则
const rules = reactive({
    password: [
        { required: true, message: '请输入原密码', trigger: 'blur' },
    ],
    rePassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
    ]
})
//修改密码
const modifyPassword = async () => {
    if (modifyData.oldPassword && modifyData.newPassword) {
        if (modifyData.oldPassword !== modifyData.newPassword) {
            const res = await changePassword(userStore.id, modifyData.oldPassword, modifyData.newPassword)
            if (res.data.status === 0) {
                ElMessage.success('修改密码成功')
                state.changeTip = false
                router.replace('/login')
            } else {
                ElMessage.error('修改密码失败')
            }
        } else {
            ElMessage.error('新旧密码必须不同')
        }
    }else{
        ElMessage.error('请输入新旧密码')
    }
}

</script>

<template>
    <el-dialog v-model="state.changeTip" title="修改密码" width="400px">
        <el-form class="register-form" label-position="top" :rules="rules">
            <el-form-item label="原始密码" prop="password">
                <el-input placeholder="输入你的原始密码" showPassword v-model="modifyData.oldPassword"></el-input>
            </el-form-item>
            <el-form-item label="新密码" prop="rePassword">
                <el-input placeholder="输入你的新密码" showPassword v-model="modifyData.newPassword"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="state.changeTip = false">取消</el-button>
                <el-button type="primary" @click="modifyPassword">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<style scoped lang="sass">

</style>